package com.zhugang.week02;

/**
 * @program algorithms
 * @description: mergeTwoLists
 * @author: chanzhugang
 * @create: 2022/04/18 23:54
 */
public class MergeTwoLists {

    public class ListNode {
        public int val;
        public ListNode next;

        public ListNode() {
        }
    }

    /**
     * 剑指offer25. 合并两个有序链表
     * 开辟结果链表，遍历p1、p2链表比较大小，小的节点往结果链表尾部插入，剩余节点全部追加尾部
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        // 开辟新链表，比较两个有序链表，小的节点尾部插入
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode virtualNode = new ListNode();
        ListNode tail = virtualNode;
        ListNode p1 = l1;
        ListNode p2 = l2;
        while (p1 != null && p2 != null) {
            if (p1.val <= p2.val) {
                tail.next = p1;
                tail = p1;
                p1 = p1.next;
            } else {
                tail.next = p2;
                tail = p2;
                p2 = p2.next;
            }
        }
        if (p1 != null) tail.next = p1;
        if (p2 != null) tail.next = p2;
        return virtualNode.next;
    }

}